package com.student.gateway.controller;

import com.student.common.entity.Result;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.reactive.function.client.WebClient;
import reactor.core.publisher.Mono;

import java.util.HashMap;
import java.util.Map;

/**
 * 统计数据控制器
 * 提供系统首页统计数据API
 * 
 * @author student
 * @date 2025
 */
@RestController
@RequestMapping("/statistics")
@CrossOrigin(origins = "*")
public class StatisticsController {
    
    @Autowired
    private WebClient webClient;
    
    // 各服务的基础URL
    private static final String STUDENT_SERVICE_URL = "http://student-service";
    private static final String TEACHER_SERVICE_URL = "http://teacher-service";
    private static final String COURSE_SERVICE_URL = "http://course-service";
    private static final String ENROLLMENT_SERVICE_URL = "http://enrollment-service";
    
    /**
     * 获取系统统计数据
     */
    @GetMapping
    public Result<Map<String, Object>> getStatistics() {
        try {
            Map<String, Object> statistics = new HashMap<>();
            
            // 获取学生总数
            Long studentCount = getStudentCountInternal();
            statistics.put("studentCount", studentCount != null ? studentCount : 0);
            
            // 获取教师总数
            Long teacherCount = getTeacherCountInternal();
            statistics.put("teacherCount", teacherCount != null ? teacherCount : 0);
            
            // 获取课程总数
            Long courseCount = getCourseCountInternal();
            statistics.put("courseCount", courseCount != null ? courseCount : 0);
            
            // 获取选课总数
            Long enrollmentCount = getEnrollmentCountInternal();
            statistics.put("enrollmentCount", enrollmentCount != null ? enrollmentCount : 0);
            
            return Result.success(statistics);
        } catch (Exception e) {
            return Result.error("获取统计数据失败：" + e.getMessage());
        }
    }
    
    /**
     * 获取学生总数
     */
    @GetMapping("/student/count")
    public Result<Long> getStudentCount() {
        try {
            Long count = getStudentCountInternal();
            return Result.success(count != null ? count : 0L);
        } catch (Exception e) {
            return Result.error("获取学生总数失败：" + e.getMessage());
        }
    }
    
    /**
     * 获取教师总数
     */
    @GetMapping("/teacher/count")
    public Result<Long> getTeacherCount() {
        try {
            Long count = getTeacherCountInternal();
            return Result.success(count != null ? count : 0L);
        } catch (Exception e) {
            return Result.error("获取教师总数失败：" + e.getMessage());
        }
    }
    
    /**
     * 获取课程总数
     */
    @GetMapping("/course/count")
    public Result<Long> getCourseCount() {
        try {
            Long count = getCourseCountInternal();
            return Result.success(count != null ? count : 0L);
        } catch (Exception e) {
            return Result.error("获取课程总数失败：" + e.getMessage());
        }
    }
    
    /**
     * 获取选课总数
     */
    @GetMapping("/enrollment/count")
    public Result<Long> getEnrollmentCount() {
        try {
            Long count = getEnrollmentCountInternal();
            return Result.success(count != null ? count : 0L);
        } catch (Exception e) {
            return Result.error("获取选课总数失败：" + e.getMessage());
        }
    }
    
    // 内部方法：调用各服务获取数量
    private Long getStudentCountInternal() {
        try {
            String url = STUDENT_SERVICE_URL + "/student/count";
            System.out.println("调用学生服务URL: " + url);
            Result<Long> result = webClient.get()
                    .uri(url)
                    .retrieve()
                    .bodyToMono(Result.class)
                    .block();
            System.out.println("学生服务响应: " + result);
            return result != null && result.getCode() == 200 ? (Long) result.getData() : 0L;
        } catch (Exception e) {
            System.err.println("调用学生服务失败：" + e.getMessage());
            e.printStackTrace();
            return 0L;
        }
    }
    
    private Long getTeacherCountInternal() {
        try {
            String url = TEACHER_SERVICE_URL + "/teacher/count";
            System.out.println("调用教师服务URL: " + url);
            Result<Long> result = webClient.get()
                    .uri(url)
                    .retrieve()
                    .bodyToMono(Result.class)
                    .block();
            System.out.println("教师服务响应: " + result);
            return result != null && result.getCode() == 200 ? (Long) result.getData() : 0L;
        } catch (Exception e) {
            System.err.println("调用教师服务失败：" + e.getMessage());
            e.printStackTrace();
            return 0L;
        }
    }
    
    private Long getCourseCountInternal() {
        try {
            String url = COURSE_SERVICE_URL + "/course/count";
            System.out.println("调用课程服务URL: " + url);
            Result<Long> result = webClient.get()
                    .uri(url)
                    .retrieve()
                    .bodyToMono(Result.class)
                    .block();
            System.out.println("课程服务响应: " + result);
            return result != null && result.getCode() == 200 ? (Long) result.getData() : 0L;
        } catch (Exception e) {
            System.err.println("调用课程服务失败：" + e.getMessage());
            e.printStackTrace();
            return 0L;
        }
    }
    
    private Long getEnrollmentCountInternal() {
        try {
            String url = ENROLLMENT_SERVICE_URL + "/enrollment/count";
            System.out.println("调用选课服务URL: " + url);
            Result<Long> result = webClient.get()
                    .uri(url)
                    .retrieve()
                    .bodyToMono(Result.class)
                    .block();
            System.out.println("选课服务响应: " + result);
            return result != null && result.getCode() == 200 ? (Long) result.getData() : 0L;
        } catch (Exception e) {
            System.err.println("调用选课服务失败：" + e.getMessage());
            e.printStackTrace();
            return 0L;
        }
    }
}
